<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择退货仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct"
                >新增行</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除行</el-button
              >
            </template>
            <template v-slot:filter-productCodeScan>
              <div class="scan-input-box">
                <ScanInputBox
                  v-model:query="scanInfo.query"
                  :api="scanInfo.api"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </div>
            </template>
          </NewPageFilter>

          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <PageTable
                ref="table"
                :class="{
                  isShow:
                    selectProductInfo.popoVisible ||
                    selectBatchInfo.popoVisible,
                }"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :spanMethod="spanMethod"
                :tabIndex="false"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                methodKey="groupKey"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-commonName="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    "
                    :ref="'productRef' + scope.$index"
                    :class="'productKey' + scope.$index"
                    class="productKey"
                    :disabled="!canAddProduct"
                    placeholder="名称\编码\规格\批号"
                    v-model="scope.row.productKeyword"
                    @keyup.enter="productSearchInput(scope.row, scope.$index)"
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="productSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <span v-else>{{ scope.row.commonName }}</span>
                </template>
                <template v-slot:col-storeBatchNumber="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType &&
                      (scope.row.emptyRowType === '1' ||
                        scope.row.emptyRowType === '2') &&
                      (formInfo.isCargoSpaceManage === 1
                        ? scope.row.emptyRowType
                        : !scope.row.codeType ||
                          scope.row.codeType === 1 ||
                          scope.row.codeType === 4)
                    "
                    :ref="'batchRef' + scope.$index"
                    :class="'batchKey' + scope.$index"
                    class="batchKey"
                    placeholder="入库批次\供应商名称"
                    :disabled="!scope.row.depotStockId"
                    v-model="scope.row.batchKeyword"
                    @keyup.enter="
                      batchNumberSearchInput(scope.row, scope.$index)
                    "
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="batchNumberSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <template v-else>
                    <StoreBatchNumberTag :row="scope.row" />
                  </template>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    class="margin-bottom"
                    v-if="
                      formInfo.isCargoSpaceManage === 1
                        ? !scope.row.emptyRowType
                        : (scope.row.codeType === 1 ||
                            scope.row.codeType === 4) &&
                          !scope.row.emptyRowType
                    "
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div> -->
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="
                                changeSmall(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.smallUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div> -->
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span
                    v-else-if="
                      formInfo.isCargoSpaceManage === 1
                        ? false
                        : (scope.row.codeType === 2 ||
                            scope.row.codeType === 3) &&
                          !scope.row.emptyRowType
                    "
                    >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                  >
                </template>
                <template v-slot:col-reasonValue="scope">
                  <el-form-item
                    v-if="!scope.row.emptyRowType"
                    class="margin-bottom"
                    :prop="`data.${scope.$index}.reason`"
                  >
                    <SelectModel
                      v-model.lazy="scope.row.reason"
                      style="margintop: 18px"
                      type-code="purch_return_reason"
                    />
                  </el-form-item>
                </template>

                <template v-slot:col-receiptNumber="scope">
                  <el-input
                    v-if="
                      scope.row.isConsignBusiness != 1 &&
                      !scope.row.emptyRowType
                    "
                    v-model="scope.row.receiptNumber"
                    :maxlength="50"
                  ></el-input>
                  <span v-else-if="!scope.row.emptyRowType">{{
                    scope.row.receiptNumber || '-'
                  }}</span>
                </template>
                <template v-slot:col-receiptPrice="scope">
                  <el-form-item
                    v-if="
                      scope.row.isConsignBusiness != 1 &&
                      !scope.row.emptyRowType
                    "
                    :prop="`data.${scope.$index}[receiptPrice]`"
                  >
                    <el-input-number
                      v-model="scope.row.receiptPrice"
                      controls-position="right"
                      style="minwidth: 100px; margintop: 18px"
                      :precision="systemConfig.price_precision"
                      :step="1"
                      :min="0"
                      :max="999999999999999"
                      @change="
                        changePrice(
                          $event,
                          `data.${scope.$index}.receiptPrice`,
                          scope.row
                        )
                      "
                    />
                  </el-form-item>
                  <span v-else-if="!scope.row.emptyRowType">{{
                    scope.row.receiptPrice || '-'
                  }}</span>
                </template>
                <template v-slot:col-receiptCalcQty="scope">
                  <el-form-item
                    v-if="
                      scope.row.isConsignBusiness != 1 &&
                      !scope.row.emptyRowType
                    "
                    :prop="`data.${scope.$index}.receiptCalcQty`"
                  >
                    <el-input-number
                      v-model.lazy="scope.row.receiptCalcQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.qty_show_precision"
                      :min="0"
                      :max="scope.row.qty"
                    />
                  </el-form-item>
                  <span v-else-if="!scope.row.emptyRowType">{{
                    scope.row.receiptCalcQty || '-'
                  }}</span>
                </template>
              </PageTable>
            </el-form>
          </div>
          <SelectProduct
            v-if="selectProductInfo.visible"
            v-model:showDialog="selectProductInfo.visible"
            :tableKey="selectProductInfo.tableKey"
            :query="selectProductInfo.query"
            :highlightRow="false"
            :checkBox="true"
            :showPrice="$permission('transferOrder:price')"
            @callback="selectProductBackList"
          />
          <SelectBatch
            v-if="selectBatchInfo.visible"
            v-model:showDialog="selectBatchInfo.visible"
            :popoVisible="selectBatchInfo.visible"
            :tableKey="selectBatchInfo.tableKey"
            :query="selectBatchInfo.query"
            :codeType="selectBatchInfo.row.codeType"
            :highlightRow="false"
            :checkBox="true"
            :showPrice="$permission('transferOrder:price')"
            @callback="selectBatchBackList"
          ></SelectBatch>
          <el-popover
            v-if="selectProductInfo.popoVisible"
            ref="productPopoverRef"
            popper-class="popover-wrapper"
            placement="bottom-start"
            :virtual-ref="productRef"
            width="1000px"
            :visible="selectProductInfo.popoVisible"
            virtual-triggering
            @hide="productPopoHide"
          >
            <ProductTable
              v-if="selectProductInfo.popoVisible"
              :popoVisible="selectProductInfo.popoVisible"
              :tableKey="selectProductInfo.tableKey"
              :query="selectProductInfo.query"
              :highlightRow="selectProductInfo.highlightRow"
              :checkBox="selectProductInfo.checkBox"
              :refresh="selectProductInfo.refresh"
              :showPrice="$permission('transferOrder:price')"
              tableType="product"
              @checkMore="checkMore('product')"
              @reset="selectProductInfo.popoVisible = false"
              @callback="selectProductBack"
              @keyDown="productKeyDown"
            ></ProductTable>
          </el-popover>
          <el-popover
            v-if="selectBatchInfo.popoVisible"
            ref="batchPopoverRef"
            :virtual-ref="batchRef"
            popper-class="popover-wrapper"
            placement="bottom-start"
            width="600px"
            :visible="selectBatchInfo.popoVisible"
            virtual-triggering
            @hide="batchPopoHide"
          >
            <ProductTable
              v-if="selectBatchInfo.popoVisible"
              :popoVisible="selectBatchInfo.popoVisible"
              :tableKey="selectBatchInfo.tableKey"
              :query="selectBatchInfo.query"
              :highlightRow="selectBatchInfo.highlightRow"
              :checkBox="selectBatchInfo.checkBox"
              :refresh="selectBatchInfo.refresh"
              :showPrice="$permission('transferOrder:price')"
              :codeType="selectBatchInfo.row.codeType"
              tableType="batch"
              @checkMore="checkMore('batch')"
              @reset="selectBatchInfo.popoVisible = false"
              @callback="selectBatchBack"
              @keyDown="batchKeyDown"
            ></ProductTable>
          </el-popover>
        </div>
      </div>
    </NewFullScreen>
    <!--           在供货目录中 根据产品选择供应商 -->
    <SelectSupplier
      v-if="selectProductSupplier.visible"
      v-model:show-dialog="selectProductSupplier.visible"
      v-model:query="selectProductSupplier.query"
      :check-box="false"
      :highlight-row="true"
      :api="selectProductSupplier.api"
      @callback="selectSupplierCallback"
    />
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:showDialog="depotInfo.visible"
      :checkBox="false"
      v-model:query="depotInfo.query"
      :highlightRow="true"
      :saveEmpty="true"
      @callback="selectDepotCallBack"
    />
    <!-- 个体操作 -->
    <BatchIndividual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :leftApi="individualInfo.leftApi"
      :rightApi="individualInfo.rightApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQuery="individualInfo.leftQuery"
      :rightQuery="individualInfo.rightQuery"
      :details="individualInfo.details"
      :isRequest="individualInfo.isRequest"
      :isGetRightList="!!purchReturnId"
      :showPrice="$permission('transferOrder:price')"
      @callback="individualCallback"
    ></BatchIndividual>
  </div>
  <SelectContract
    v-if="contractInfo.visible"
    v-model:showDialog="contractInfo.visible"
    :checkBox="false"
    :query="contractInfo.query"
    :data="contractInfo.data"
    :changeContract="contractInfo.changeContract"
    :highlightRow="true"
    :saveEmpty="true"
    @callback="selectContractCallBack"
  />
</template>

<script setup name="purchReturnModify">
import SelectProduct from './components/SelectProduct'
import SelectBatch from './components/SelectBatch'
import BatchIndividual from './components/BatchIndividual'
import ProductTable from './components/ProductTable'
import StoreBatchNumberTag from './components/StoreBatchNumberTag'
import moment from 'moment'
import { getDepotStockCustomizeListPage } from '@/api/stock'
import _ from 'lodash'
import {
  detailPurchReturn,
  purchReturnDetailsCustomizeListAll,
  updatePurchReturnOrder,
  createPurchReturnOrder,
  createPurchReturnOrderAndSave,
  getPurchReturnOrderDetail,
} from '@/api/purch'
import { getCoreSystemConfigAll } from '@/api/core'
import { getSupplierPage } from '@/api/core'
import { depotStockCustomizeScan } from '@/api/stock'
import ScanInputBox from './components/ScanInputBox'
import { getCustomizeSetting } from '@/api/customize'
import SelectContract from './selectContract'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import { setVal, setTabindex } from '@/common/js/base'
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  purchReturnId: {
    type: [Number, String],
  },
  purchAccording: {
    type: [Number, String],
  },
})
const scanInfo = ref({
  api: depotStockCustomizeScan,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      supplierId: '',
      // validateExpire: false
      purchAccording:
        props.purchAccording ||
        proxy.$store.state.permission.systemConfig.purch_according,
    },
  },
})
const formRefs = ref([])
const productPopoverRef = ref()
const productRef = ref()
const batchPopoverRef = ref()
const batchRef = ref()
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    // receiveAddressValue:'',
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    supplierName: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.name
      : '',
    supplierId: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.id
      : '',
    purchAccording:
      props.purchAccording ||
      proxy.$store.state.permission.systemConfig.purch_according,
  },
  fieldList: [
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '退货仓库', value: 'depotName', type: 'slot' },
    { label: '部门', value: 'deptName', type: 'input', disabled: true },

    {
      label: '采购退货类型',
      value: 'returnType',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'purch_return_type',
    },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '退货联系人', value: 'contact', type: 'input', maxlength: 32 },
    { label: '联系人电话', value: 'phone', type: 'input' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.purchReturnId &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '采购依据',
      value: 'purchAccording',
      type: 'select-model',
      code: 'purch_according',
      disabled: true,
    },
    // {label: '收货地址', value: 'receiveAddressValue', type: 'slot'},
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    // receiveAddressValue:[{required : true, message: '请选择收货地址', target: 'change'}],
    deptName: [{ required: true, message: '请输入部门', trigger: 'blur' }],
    returnType: [
      {
        required: true,
        message: '请选择采购退货类型',
        target: 'change',
      },
    ],
    depotName: [{ required: true, message: '请选择仓库', target: 'change' }],
    supplierName: [
      { required: true, message: '请选择供应商', target: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'change,blur' }],
  },
  labelWidth: '120px',
  isCargoSpaceManage: 0, //1货位货位管理,0非货位管理,只判断出库仓库
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    { type: 'slot', value: 'productCodeScan', show: true },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  batchSysGroup: [],
  data: [
    {
      emptyRowType: '1', //1添加产品和批次，2添加批次
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '通用名称',
      value: 'commonName',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '产品编码',
      value: 'productCode',
      width: '100px',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '包装规格',
      value: 'packingSpecification',
    },
    {
      label: '厂家',
      value: 'brandName',
      width: '80px',
    },
    {
      label: '单位',
      value: 'unitName',
      width: '80px',
    },
    {
      label: '批号',
      value: 'batchNumber',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      width: '80px',
    },
    {
      label: '失效日期',
      value: 'validityDate',
      width: '80px',
    },
    {
      label: '入库批次号',
      align: 'left',
      value: 'storeBatchNumber',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchReturn:price'),
      width: '60px',
    },
    {
      label: '可用数',
      value: 'stockAvailableQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
      width: '60px',
    },

    {
      label: '退货数量',
      value: 'qty',
      type: 'slot',
      width: '160px',
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchReturn:price'),
      width: '80px',
    },
    {
      label: '退货原因',
      value: 'reasonValue',
      asValue: 'reason',
      type: 'slot',
    },
    {
      label: '纸质发票号',
      value: 'receiptNumber',
      type: 'slot',
    },
    {
      label: '开票数量',
      value: 'receiptCalcQty',
      type: 'slot',
    },
    {
      label: '开票单价',
      value: 'receiptPrice',
      type: 'slot',
      permission: !proxy.$permission('purchReturn:price'),
    },
    {
      label: '开票金额',
      value: 'receiptSumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchReturn:price'),
    },
    {
      label: '引用合同单号',
      value: 'quoteContractNo',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
        ifRender: ifRenderIndividual,
      },
      {
        label: '新增',
        event: addBucth,
        show: true,
        ifRender: ifRenderAddButch,
      },
      {
        label: '删除',
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return !row.emptyRowType
        },
      },
      {
        label: '切换合同',
        event: changeContract,
        show: true,
        ifRender: function (row) {
          return !row.emptyRowType
        },
        // ifRender: function (row) {
        //   return row.contractVOList && row.contractVOList.length > 1;
        // },
      },
    ],
  },
  bigWidth: {
    productCode: '100px',
    standard: '60px',
    brandName: '80px',
    unitName: '80px',
    batchNumber: '100px',
    productionDate: '80px',
    validityDate: '80px',
    supplierName: '80px',
    price: '80px',
    stockAvailableQty: '60px',
    qty: '140px',
    sumAmount: '80px',
  },
  smallWidth: {
    productCode: '90px',
    standard: '60px',
    brandName: '60px',
    unitName: '40px',
    batchNumber: '60px',
    productionDate: '50px',
    validityDate: '80px',
    supplierName: '60px',
    price: '50px',
    stockAvailableQty: '50px',
    qty: '90px',
    sumAmount: '70px',
    reasonValue: '100px',
    receiptNumber: '100px',
    receiptCalcQty: '100px',
    receiptPrice: '100px',
  },
})
const fullInfo = ref({
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show:
        !props.purchReturnId && proxy.$permission('purchReturn:saveAndSubmit'),
    },
    { label: '保存', event: save, show: true },
  ],
})
const selectSupplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: 'supplierId',
  },
})
//在供货目录中 根据产品id选择供应商
const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    supplierAuth: 'supplierId',
  },
})
const index = ref('')

const contractInfo = ref({
  visible: false,
  changeContract: false,
  query: {},
  data: [],
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const depotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: '1',
    useTypeId: '1',
  },
})

const selectProductInfo = ref({
  //库存产品
  tableKey:
    'productPurchReturnPageAddProduct-com.slip.spd.entity.vo.stock.DepotStockVO',
  visible: false,
  popoVisible: false,
  highlightRow: true,
  checkBox: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    excludeQueryList: [], //库存产品左侧过滤配置
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      generalProductCategory: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isDepotSearchLeft: 1,
      purchAccording:
        props.purchAccording ||
        proxy.$store.state.permission.systemConfig.purch_according,
    },
  },
})
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    excludeQueryList: [],
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      productionDate: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      validityDate: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      isDepotSearchRight: 1,
      stockSearchKey: '',
      groupField: '',
      purchAccording:
        props.purchAccording ||
        proxy.$store.state.permission.systemConfig.purch_according,
    },
  },
  tableKey:
    'productPurchReturnPageAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO',
  highlightRow: true,
  checkBox: false,
})

const individualInfo = ref({
  //个体操作
  visible: false,
  isRequest: false,
  row: {},
  details: [],
  index: '',
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      isDepotSearchRight: 1,
      groupField: '',
      purchAccording:
        props.purchAccording ||
        proxy.$store.state.permission.systemConfig.purch_according,
    },
  }, //个体弹窗左边数据查询条件
  rightQuery: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.purchReturnId || '',
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  }, //个体弹窗右边数据查询条件
  rightApi: purchReturnDetailsCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
  leftTableKey:
    'purchPurchReturnProductIndividualLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'purchPurchReturnProductIndividualRight-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
})
const isActive = ref(false)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        row.receiptSumAmount = proxy.$fn.accMul(
          row.receiptPrice || 0,
          row.receiptCalcQty || 0
        )
      })
      let list = []
      tableInfo.value.data.forEach((item, index) => {
        if (item.emptyRowType && item.emptyRowType === '1') {
          let arr = [
            { key: 'productKey' + index, index: index },
            { key: 'batchKey' + index, index: index },
          ]
          list = list.concat(arr)
        } else if (item.emptyRowType && item.emptyRowType === '2') {
          list.push({ key: 'batchKey' + index, index: index })
        }
        let depotStockIds = []
        if (item.details && item.details.length) {
          depotStockIds = item.details.map((el) => el.depotStockId)
        } else {
          if (item.groupConcatDepotStockIds) {
            depotStockIds.push(item.groupConcatDepotStockIds)
          }
        }
        item.groupConcatDepotStockIds = depotStockIds.length
          ? depotStockIds.toString()
          : ''
      })
      tableInfo.value.tabList = list
      setTabindex(proxy)
      setSuplierIdMap()
    }
  },
  { deep: true }
)

watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false
    }
  }
)
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false
    }
  }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canAddProduct = computed(() => {
  return (
    formInfo.value.data.depotName &&
    formInfo.value.data.deptName &&
    formInfo.value.data.supplierName
  )
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

window.addEventListener('click', closePopper, { passive: true })
window.addEventListener('keydown', addTab, true)
onActivated(() => {
  window.addEventListener('click', closePopper, { passive: true })
  window.addEventListener('keydown', addTab, true)
})
onDeactivated(() => {
  window.removeEventListener('click', closePopper, true)
  window.removeEventListener('keydown', addTab, true)
})
function addTab(val) {
  if (val.key === 'Tab') {
    if (!formInfo.value.data.depotName) {
      openDepotWindow()
      return
    }
    if (!formInfo.value.data.supplierName) {
      openSupplierWindow()
      return
    }
  }
}
function closePopper(e) {
  if (
    e.target.closest('.el-popper') ||
    e.target.closest('.productKey') ||
    e.target.closest('.batchKey')
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false
    selectProductInfo.value.popoVisible = false
  }
}

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
// 用于存储groupKey对应批次数量
const groupKeyMap = ref({})
function setSuplierIdMap() {
  let _data = tableInfo.value.data.filter((element) => {
    return element.groupKey
  })
  groupKeyMap.value = _.groupBy(_data, 'groupKey')
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.value.fieldList.length
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage //1货位管理，0非货位管理
  if (row.emptyRowType !== '1' || !row.emptyRowType) {
    let afterIndexs = []
    if (isCargoSpaceManage == 0) {
      afterIndexs = row.codeType === 2 || row.codeType === 3 ? [len + 1] : []
    }
    let keys = new Array(len + 2)
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = 'groupKey'
    } else {
      keys = [
        'groupKey',
        'commonName',
        'productCode',
        'standard',
        'brandName',
        'unitName',
        // 'codeTypeValue',
        'batchNumber',
        'productionDate',
        'validityDate',
      ]
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(
      tableInfo.value.data,
      keys,
      rowIndex,
      columnIndex
    )
  }
}
function checkMore(str) {
  if (str === 'product') {
    let row = selectProductInfo.value.row
    let index = selectProductInfo.value.index
    productSearch(row, index)
  } else if (str === 'batch') {
    let row = selectBatchInfo.value.row
    let index = selectBatchInfo.value.index
    batchNumberSearch(row, index)
  }
}
function productSearchInput(row, index) {
  //产品enter查询
  if (!formInfo.value.data.depotName) {
    return
  }
  if (!formInfo.value.data.supplierName) {
    return
  }
  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  productRef.value = proxy.$refs['productRef' + index]
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.query.queryMap.depotId.value =
    formInfo.value.data.depotId
  selectProductInfo.value.query.queryMap.supplierId.value =
    formInfo.value.data.supplierId
  selectProductInfo.value.refresh = Math.random()
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  selectProductInfo.value.popoVisible = true
}
function productSearch(row, index) {
  //产品点击查询图标
  if (!formInfo.value.data.depotName) {
    return
  }
  if (!formInfo.value.data.supplierName) {
    return
  }
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.query.queryMap.depotId.value =
    formInfo.value.data.depotId
  selectProductInfo.value.query.queryMap.supplierId.value =
    formInfo.value.data.supplierId
  selectProductInfo.value.visible = true
  selectProductInfo.value.popoVisible = false
}
function batchNumberSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    if (!row.depotStockId) return
    let className = 'batchKey' + index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.focus()
    let isCargoSpaceManage = formInfo.value.isCargoSpaceManage
    batchRef.value = proxy.$refs['batchRef' + index]
    selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
    selectBatchInfo.value.refresh = Math.random()
    selectBatchInfo.value.row = row
    selectBatchInfo.value.index = index
    let batchSysGroup = tableInfo.value.batchSysGroup
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    let ids = []
    let excludeQueryList = []
    if (list.length) {
      list.forEach((row) => {
        if (isCargoSpaceManage === 1) {
          console.log(!row.emptyRowType)
          if (!row.emptyRowType) {
            let arr = []
            batchSysGroup.forEach((el) => {
              let obj = {}
              obj.columnName = el.columnName
              obj.asTbName = el.asTbName
              obj.ignoreEmptyValue = false
              obj.value = row[el.key]
              arr.push(obj)
            })
            excludeQueryList.push(arr)
          }
        } else {
          if (row.groupConcatDepotStockIds) {
            ids.push(item.groupConcatDepotStockIds)
          }
        }
      })
    }
    if (isCargoSpaceManage === 1) {
      selectBatchInfo.value.query.excludeQueryList = excludeQueryList
    }

    selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
    selectBatchInfo.value.query.queryMap.productId.value = row.productId
    if (row.batchNumber) {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.batchNumber,
      }
    } else {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'NULL',
        queryCategory: 'AND',
        value: '',
      }
    }
    if (row.validityDate) {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.validityDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }
    if (row.productionDate) {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.productionDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }

    selectBatchInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : ''
    selectBatchInfo.value.query.queryMap.depotId.value =
      formInfo.value.data.depotId
    selectBatchInfo.value.query.queryMap.supplierId.value =
      formInfo.value.data.supplierId
    selectBatchInfo.value.popoVisible = true
    clearTimeout(timer)
  }, 0)
}
function batchNumberSearch(row, index) {
  //批次点击查询图标
  if (!row.depotStockId) return
  selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
  selectBatchInfo.value.row = row
  selectBatchInfo.value.index = index
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage
  let batchSysGroup = tableInfo.value.batchSysGroup
  let list = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let ids = []
  let excludeQueryList = []
  if (list.length) {
    list.forEach((row) => {
      if (isCargoSpaceManage === 1) {
        if (!row.emptyRowType) {
          let arr = []
          batchSysGroup.forEach((el) => {
            let obj = {}
            obj.columnName = el.columnName
            obj.asTbName = el.asTbName
            obj.ignoreEmptyValue = false
            obj.value = row[el.key]
            arr.push(obj)
          })
          excludeQueryList.push(arr)
        }
      } else {
        if (row.groupConcatDepotStockIds) {
          ids.push(row.groupConcatDepotStockIds)
        }
      }
    })
  }
  if (isCargoSpaceManage === 1) {
    selectBatchInfo.value.query.excludeQueryList = excludeQueryList
  }

  selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
  selectBatchInfo.value.query.queryMap.productId.value = row.productId
  if (row.batchNumber) {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }

  selectBatchInfo.value.query.queryMap.id.value = ids.length
    ? ids.toString()
    : ''
  selectBatchInfo.value.query.queryMap.depotId.value =
    formInfo.value.data.depotId
  selectBatchInfo.value.query.queryMap.supplierId.value =
    formInfo.value.data.supplierId
  selectBatchInfo.value.visible = true
  selectBatchInfo.value.popoVisible = false
}
function countData(data) {
  if (data.stockAvailableCalcQty > data.unitConvertCoefficient) {
    data.calcQty = data.unitConvertCoefficient
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  } else {
    data.calcQty = data.stockAvailableCalcQty
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  }
  data._key =
    data.storeBatchNumber +
    '-' +
    data.supplierId +
    '-' +
    data.price +
    '-' +
    data.isConsignBusiness
  groupKeyMap.value[data.supplierId] = 1

  return data
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index
  let newData = data.map((item) => {
    if (item.groupConcatIds.includes(',')) {
      return {
        commonName: item.commonName,
        productCode: item.productCode,
        groupKey: item.groupKey,
        standard: item.standard,
        brandName: item.brandName,
        brandId: item.brandId,
        unitName: item.unitName,
        unitId: item.unitId,
        codeTypeValue: item.codeTypeValue,
        codeType: item.codeType,
        batchNumber: item.batchNumber,
        productionDate: item.productionDate,
        validityDate: item.validityDate,
        depotStockId: item.depotStockId,
        productId: item.productId,
        orgId: item.orgId,
        packingSpecification: item.packingSpecification,
        emptyRowType: '2',
      }
    } else {
      item = countData(item)
      item.details = [proxy.$fn.deepClone(item)]
      return item
    }
  })
  let emptyRowTypeList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  ) //空行条数
  let list = proxy.$fn.deepClone(tableInfo.value.data)
  let leftList,
    rightList = []
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.value.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index)
      rightList = list.slice(index)
    } else {
      leftList = list.slice(0, index)
      rightList = list.slice(index + 1)
    }
  } else {
    leftList = list.slice(0, index)
    rightList = list.slice(index)
  }
  tableInfo.value.data = leftList.concat(newData).concat(rightList)
  console.log(tableInfo.value.data)
}
function countQty(data) {
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  if (data.details && data.details.length) {
    data.details.forEach((el) => {
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, el.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, el.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0)
    })
  }
  data.largeUnitQty = largeUnitQty
  data.smallUnitQty = smallUnitQty
  data.calcQty = calcQty
  data.qty = proxy.$fn.accDiv(calcQty, data.unitConvertCoefficient || 1)
  data.sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(calcQty, data.price || 0),
    data.unitConvertCoefficient || 1
  )
  return data
}
function selectBatchBackList(data) {
  let row = selectBatchInfo.value.row
  let index = selectBatchInfo.value.index
  data.forEach((item) => {
    item = countData(item)
  })
  let groupData = _.groupBy(data, '_key')
  let groupKeys = Object.keys(groupData)
  let groupKeysIn = []
  tableInfo.value.data.forEach((item) => {
    if (item.groupKey === row.groupKey) {
      if (item._key) {
        if (groupKeys.includes(item._key)) {
          groupKeysIn.push(item._key)
          item.details = item.details.concat(groupData[item._key])
          item = countQty(item)
        }
      }
    }
  })
  let list = []
  if (groupKeysIn.length) {
    groupKeys.forEach((item) => {
      if (!groupKeysIn.includes(item)) {
        let groupDataItem = groupData[item]
        let obj = proxy.$fn.deepClone(groupDataItem[0])
        obj.details = proxy.$fn.deepClone(groupDataItem)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        // obj.reason = row.reason
        // obj.receiptPrice = row.receiptPrice
        // obj.receiptNumber = row.receiptNumber
        if (
          parseInt(props.purchAccording) === 2 ||
          parseInt(purchAccording.value) === 2
        ) {
          obj.quoteContractNo = row.quoteContractNo || obj.quoteContractNo
          obj.contractId = row.contractId || obj.contractId
        }

        list.push(obj)
      }
    })
  } else {
    let values = Object.values(groupData)
    values.forEach((item) => {
      let obj = proxy.$fn.deepClone(item[0])
      obj.details = proxy.$fn.deepClone(item)
      obj.groupKey = row.groupKey
      obj = countQty(obj)
      obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
      obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
      // obj.reason = row.reason
      // obj.receiptPrice = row.receiptPrice
      // obj.receiptNumber = row.receiptNumber
      if (
        parseInt(props.purchAccording) === 2 ||
        parseInt(purchAccording.value) === 2
      ) {
        obj.quoteContractNo = row.quoteContractNo || obj.quoteContractNo
        obj.contractId = row.contractId || obj.contractId
      }

      list.push(obj)
    })
  }
  if (list.length) {
    let newData = tableInfo.value.data[index]
    let leftList = []
    if (newData._key) {
      leftList = tableInfo.value.data.slice(0, index + 1)
    } else {
      leftList = tableInfo.value.data.slice(0, index)
    }
    let rightList = tableInfo.value.data.slice(index + 1)
    tableInfo.value.data = leftList.concat(list).concat(rightList)
  }
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'productKey' + selectProductInfo.value.index
      setVal(className)
      selectProductInfo.value.popoVisible = false
      return
    }
    let className = 'productKey' + selectProductInfo.value.index
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    productKeyDom.blur()
  })
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index
  if (obj.groupConcatIds.includes(',')) {
    tableInfo.value.data[index] = {
      commonName: obj.commonName,
      productCode: obj.productCode,
      groupKey: obj.groupKey,
      standard: obj.standard,
      brandName: obj.brandName,
      brandId: obj.brandId,
      unitName: obj.unitName,
      unitId: obj.unitId,
      codeTypeValue: obj.codeTypeValue,
      codeType: obj.codeType,
      batchNumber: obj.batchNumber,
      productionDate: obj.productionDate,
      validityDate: obj.validityDate,
      depotStockId: obj.depotStockId,
      orgId: obj.orgId,
      productId: obj.productId,
      emptyRowType: '2',
    }
  } else {
    obj = countData(obj)
    tableInfo.value.data[index] = proxy.$fn.deepClone(obj)
    tableInfo.value.data[index].details = [proxy.$fn.deepClone(obj)]
  }
  let itemList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  )
  if (!itemList.length) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index
  let row = selectBatchInfo.value.row
  let data = proxy.$fn.deepClone(tableInfo.value.data[index])
  obj = countData(obj)
  obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
  obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
  tableInfo.value.data[index] = proxy.$fn.deepClone(obj)
  tableInfo.value.data[index].details = [proxy.$fn.deepClone(obj)]
  tableInfo.value.data[index].groupKey = data.groupKey
  // tableInfo.value.data[index].reason = data.reason
  // tableInfo.value.data[index].receiptPrice = data.receiptPrice
  // tableInfo.value.data[index].receiptNumber = data.receiptNumber
  if (
    parseInt(props.purchAccording) === 2 ||
    parseInt(purchAccording.value) === 2
  ) {
    tableInfo.value.data[index].quoteContractNo =
      data.quoteContractNo || obj.quoteContractNo
    tableInfo.value.data[index].contractId = data.contractId || obj.contractId
  }
}
function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'batchKey' + selectProductInfo.value.index
      setVal(className)
      selectBatchInfo.value.popoVisible = false
      return
    }
    let className = 'batchKey' + selectBatchInfo.value.index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.blur()
  })
}
function individualCallback(data) {
  let index = individualInfo.value.index
  let row = individualInfo.value.row
  if (data.length) {
    let groupData = _.groupBy(data, '_key')
    let groupKeys = Object.keys(groupData)
    let groupKeysIn = []
    tableInfo.value.data = tableInfo.value.data.filter((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          return groupKeys.includes(item._key)
        } else {
          return item
        }
      } else {
        return item
      }
    })
    tableInfo.value.data.forEach((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          if (groupKeys.includes(item._key)) {
            groupKeysIn.push(item._key)
            item.details = groupData[item._key]
            item = countQty(item)
          }
        }
      }
    })
    let list = []
    if (groupKeysIn.length) {
      groupKeys.forEach((item) => {
        if (!groupKeysIn.includes(item)) {
          let groupDataItem = groupData[item]
          let obj = proxy.$fn.deepClone(groupDataItem[0])
          obj.details = proxy.$fn.deepClone(groupDataItem)
          obj.groupKey = row.groupKey
          obj = countQty(obj)
          obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
          obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
          list.push(obj)
        }
      })
    } else {
      let values = Object.values(groupData)
      values.forEach((item) => {
        let obj = proxy.$fn.deepClone(item[0])
        obj.details = proxy.$fn.deepClone(item)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        list.push(obj)
      })
    }
    if (list.length) {
      let newData = tableInfo.value.data[index]
      let leftList = []
      if (newData._key) {
        leftList = tableInfo.value.data.slice(0, index + 1)
      } else {
        leftList = tableInfo.value.data.slice(0, index)
      }
      let rightList = tableInfo.value.data.slice(index + 1)
      tableInfo.value.data = leftList.concat(list).concat(rightList)
    }
  } else {
    tableInfo.value.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupKey: row.groupKey,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      batchNumber: row.batchNumber,
      productionDate: row.productionDate,
      validityDate: row.validityDate,
      depotStockId: row.depotStockId,
      productId: row.productId,
      orgId: row.orgId,
      emptyRowType: '2',
    }
    tableInfo.value.data = tableInfo.value.data.filter((item) => {
      if (row.groupKey === item.groupKey) {
        return item.emptyRowType === '2'
      } else {
        return item
      }
    })
  }
  let emptyIndex = tableInfo.value.data.findIndex(
    (item) => item.emptyRowType === '1'
  )
  if (emptyIndex === -1) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
//新增行
function addProduct() {
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
//删除产品
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let groupKeys = tableInfo.value.selections.map((item) => item.groupKey)
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => !groupKeys.includes(item.groupKey)
      )
      if (!tableInfo.value.data.length) {
        tableInfo.value.data = [
          {
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          },
        ]
      } else {
        let index = tableInfo.value.data.findIndex(
          (item) => item.emptyRowType === '1'
        )
        if (index === -1) {
          tableInfo.value.data.push({
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          })
        }
      }
      const data = proxy.$fn.deepClone(tableInfo.value.data)
      tableInfo.value.data = []
      proxy.$nextTick(() => {
        tableInfo.value.data = data
      })
    })
}

function individualDetails(row, index) {
  let list = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let depotStockIds = []
  let groupConcatId = []
  let details = []
  let isRequest = false
  if (list.length) {
    list.forEach((item) => {
      if (item.details && item.details.length) {
        details = details.concat(item.details)
      }
      if (
        !item.details &&
        item.groupConcatIds &&
        item.groupConcatDepotStockIds
      ) {
        isRequest = true
      }
      if (item.groupConcatIds) {
        groupConcatId.push(item.groupConcatIds)
      }
      if (item.groupConcatDepotStockIds) {
        depotStockIds.push(item.groupConcatDepotStockIds)
      }
    })
  }
  individualInfo.value.row = row
  individualInfo.value.details = details
  individualInfo.value.index = index
  individualInfo.value.leftQuery.queryMap.orgId.value = row.orgId
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId
  if (row.batchNumber) {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  individualInfo.value.leftQuery.queryMap.depotId.value =
    formInfo.value.data.depotId
  individualInfo.value.leftQuery.queryMap.supplierId.value =
    formInfo.value.data.supplierId
  individualInfo.value.leftQuery.queryMap.id.value = depotStockIds.length
    ? depotStockIds.toString()
    : ''
  individualInfo.value.rightQuery.queryMap.id.value = props.purchReturnId
    ? details.length
      ? ''
      : groupConcatId.toString()
    : ''
  individualInfo.value.isRequest = isRequest
  individualInfo.value.visible = true
}
function addBucth(row, index) {
  batchNumberSearch(row, index)
}
function ifRenderAddButch(row) {
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage //1货位管理，0非货位管理
  let arr = []
  if (isCargoSpaceManage == 1) {
    arr = [1, 2, 3, 4]
  } else if (isCargoSpaceManage == 0) {
    arr = [1, 4]
  }
  if (arr.includes(row.codeType)) {
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    let index = list.findIndex((item) => item._key === row._key)
    return index === list.length - 1
  }
}
function ifRenderIndividual(row) {
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage
  if (isCargoSpaceManage === 1) {
    return false
  } else if (isCargoSpaceManage === 0) {
    let arr = [2, 3]
    return arr.includes(row.codeType) && row.emptyRowType !== '1'
  }
}
function removeBatch(row, index) {
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage
  if (row.codeType === 1 || row.codeType === 4) {
    if (
      groupKeyMap.value[row.groupKey] &&
      groupKeyMap.value[row.groupKey]?.length > 1
    ) {
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => ![row].includes(item)
      )
    } else {
      tableInfo.value.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupKey: row.groupKey,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        batchNumber: row.batchNumber,
        productionDate: row.productionDate,
        validityDate: row.validityDate,
        depotStockId: row.depotStockId,
        productId: row.productId,
        orgId: row.orgId,
        emptyRowType: '2',
      }
    }
  } else if (row.codeType === 2 || row.codeType === 3) {
    if (isCargoSpaceManage === 1) {
      if (
        groupKeyMap.value[row.groupKey] &&
        groupKeyMap.value[row.groupKey]?.length > 1
      ) {
        tableInfo.value.data = tableInfo.value.data.filter(
          (item) => ![row].includes(item)
        )
      } else {
        tableInfo.value.data[index] = {
          commonName: row.commonName,
          productCode: row.productCode,
          groupKey: row.groupKey,
          standard: row.standard,
          brandName: row.brandName,
          brandId: row.brandId,
          unitName: row.unitName,
          unitId: row.unitId,
          codeTypeValue: row.codeTypeValue,
          codeType: row.codeType,
          batchNumber: row.batchNumber,
          productionDate: row.productionDate,
          validityDate: row.validityDate,
          depotStockId: row.depotStockId,
          productId: row.productId,
          orgId: row.orgId,
          emptyRowType: '2',
        }
      }
    } else if (isCargoSpaceManage === 0) {
      tableInfo.value.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupKey: row.groupKey,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        batchNumber: row.batchNumber,
        productionDate: row.productionDate,
        validityDate: row.validityDate,
        depotStockId: row.depotStockId,
        productId: row.productId,
        orgId: row.orgId,
        emptyRowType: '2',
      }
    }
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    tableInfo.value.data = tableInfo.value.data.filter((item, i) => {
      if (!list.includes(item) || index === i) {
        return item
      }
    })
  }
}
function tableCellClassName({ column, row }) {
  if (row.isChoice && column.property === 'qty') {
    return 'success-row'
  } else {
    return ''
  }
}

function changePrice(data, str, row) {
  proxy.$refs.tableForm.clearValidate(str)
  // let arr = [1, 4]
  // if (arr.includes(row.codeType)) {
  //   tableInfo.value.data.forEach((item) => {
  //     if (item.groupKey === row.groupKey) {
  //       item.receiptPrice = data
  //     }
  //   })
  // }
}
function changeContract(row, index) {
  //打开切换合同弹窗
  if (!row.contractVOList) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '没有能切换的合同',
    })
    return
  }
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
  if (!contractInfo.value.data.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '没有能切换的合同',
    })
    return
  }
  //打开切换合同弹窗
  contractInfo.value.visible = true
  contractInfo.value.selectIndex = index
  contractInfo.value.changeContract = true
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
}
function selectContractCallBack(data) {
  if (data && data.id) {
    tableInfo.value.data[contractInfo.value.selectIndex]['quoteContractNo'] =
      data.orderNo
    tableInfo.value.data[contractInfo.value.selectIndex]['contractId'] = data.id
  } else {
    tableInfo.value.data[contractInfo.value.selectIndex]['quoteContractNo'] = ''
    tableInfo.value.data[contractInfo.value.selectIndex]['contractId'] = ''
  }
  tableInfo.value.data.forEach((item) => {
    if (
      item.groupKey ===
      tableInfo.value.data[contractInfo.value.selectIndex].groupKey
    ) {
      item['quoteContractNo'] = data.orderNo || ''
      item['contractId'] = data.id || ''
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
  let isCargoSpaceManage = formInfo.value.isCargoSpaceManage //1货位管理，0非货位管理
  if (isCargoSpaceManage === 1) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  } else if (isCargoSpaceManage === 0) {
    if (row.codeType === 1 || row.codeType === 4) {
      row.calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(
          row.largeUnitQty || 0,
          row.unitConvertCoefficient || 1
        ),
        row.smallUnitQty || 0
      )
      row.qty = proxy.$fn.accDiv(
        row.calcQty || 0,
        row.unitConvertCoefficient || 1
      )
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
        row.unitConvertCoefficient || 1
      )
      row.details[0].largeUnitQty = row.largeUnitQty
      row.details[0].smallUnitQty = row.smallUnitQty
      row.details[0].calcQty = row.calcQty
      row.details[0].qty = row.qty
      row.details[0].sumAmount = row.sumAmount
    }
  }
}

function validateExpire(list = []) {
  let msg = ''
  let currentDate = moment().format('YYYY-MM-DD')
  list.forEach((item, index) => {
    if (!item.reason) {
      msg =
        msg + `第【${index + 1}】行产品【${item.commonName}】未选择退货原因<br>`
    }
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}

async function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data
  let str = ''
  mergeDetail = mergeDetail[0]
  mergeDetail.mergeStockAvailableQty = mergeDetail.stockAvailableQty
  mergeDetail.mergeStockAvailableCalcQty = mergeDetail.stockAvailableCalcQty
  detail.mergeStockAvailableQty = mergeDetail.stockAvailableQty
  detail.mergeStockAvailableCalcQty = mergeDetail.stockAvailableCalcQty
  tableInfo.value.sysGroup.forEach((item) => {
    if (
      item !== 'price' &&
      item !== 'supplierId' &&
      item !== 'storeBatchNumber' &&
      item !== 'isConsignBusiness'
    ) {
      if (item === 'productionDate' || item === 'validityDate') {
        str = str + (mergeDetail[item] || '1900-01-01') + ''
      } else {
        str = str + mergeDetail[item] + ''
      }
    }
  })
  mergeDetail.groupKey = str
  detail._key =
    detail.storeBatchNumber +
    '-' +
    detail.supplierId +
    '-' +
    detail.price +
    '-' +
    detail.isConsignBusiness
  tableInfo.value.data.forEach((item) => {
    if (item.groupKey === mergeDetail.groupKey) {
      // mergeDetail.reason = item.reason
      // mergeDetail.receiptPrice = item.receiptPrice
      // mergeDetail.receiptNumber = item.receiptNumber
      if (
        parseInt(props.purchAccording) === 2 ||
        parseInt(purchAccording.value) === 2
      ) {
        mergeDetail.quoteContractNo =
          item.quoteContractNo || mergeDetail.quoteContractNo
        mergeDetail.contractId = item.contractId || mergeDetail.contractId
      }
    }
  })
  let unitConvertCoefficient = detail.unitConvertCoefficient || 1
  if (tableInfo.value.data && tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      item.isChoice = false
    })
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === mergeDetail.groupKey
    )
    if (list.length) {
      let index = tableInfo.value.data.findIndex(
        (item) =>
          item.groupKey === mergeDetail.groupKey &&
          item._key &&
          item._key === detail._key
      )
      if (index > -1) {
        if (
          tableInfo.value.data[index].calcQty ===
          tableInfo.value.data[index].stockAvailableCalcQty
        ) {
          callback(true)
          return
        }
        if (
          props.purchReturnId &&
          !tableInfo.value.data[index].details &&
          tableInfo.value.data[index].groupConcatDepotStockIds &&
          tableInfo.value.data[index].groupConcatIds
        ) {
          let groupConcatIds = []
          tableInfo.value.data.forEach((item) => {
            if (item.groupKey === tableInfo.value.data[index].groupKey) {
              groupConcatIds.push(item.groupConcatIds)
            }
          })
          await getIndividualRight(String(groupConcatIds)).then((res) => {
            if (res) {
              tableInfo.value.data.forEach((row) => {
                let details = []
                res.forEach((item) => {
                  if (
                    row.groupConcatIds &&
                    row.groupConcatIds.includes(item.groupConcatIds)
                  ) {
                    details.push(item)
                  }
                  row.details =
                    details && details.length ? details : row.details
                })
              })
            }
          })
        }
        let haveIndex = tableInfo.value.data[index].details.findIndex(
          (item) => item.depotStockId == detail.depotStockId
        )
        if (detail.codeType === 2 || detail.codeType === 3) {
          if (haveIndex > -1) {
            callback(true)
          } else {
            tableInfo.value.data[index].details.push(detail)
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          }
        } else if (detail.codeType === 4) {
          let num = proxy.$fn.Subtr(
            tableInfo.value.data[index].stockAvailableCalcQty,
            tableInfo.value.data[index].calcQty
          )
          if (haveIndex > -1) {
            if (num > unitConvertCoefficient) {
              tableInfo.value.data[index].details[haveIndex].calcQty =
                proxy.$fn.accAdd(
                  tableInfo.value.data[index].details[haveIndex].calcQty || 0,
                  1
                )
            } else {
              tableInfo.value.data[index].details[haveIndex].calcQty =
                tableInfo.value.data[index].details[
                  haveIndex
                ].stockAvailableCalcQty
            }
            tableInfo.value.data[index].details[haveIndex].largeUnitQty =
              parseInt(
                tableInfo.value.data[index].details[haveIndex].calcQty /
                  unitConvertCoefficient
              )
            tableInfo.value.data[index].details[haveIndex].smallUnitQty =
              parseInt(
                tableInfo.value.data[index].details[haveIndex].calcQty %
                  unitConvertCoefficient
              )
            tableInfo.value.data[index].details[haveIndex].qty =
              proxy.$fn.accDiv(
                tableInfo.value.data[index].details[haveIndex].calcQty,
                unitConvertCoefficient
              )
            tableInfo.value.data[index].details[haveIndex].sumAmount =
              proxy.$fn.accDiv(
                proxy.$fn.accMul(
                  tableInfo.value.data[index].details[haveIndex].calcQty,
                  tableInfo.value.data[index].details[haveIndex].price
                ),
                unitConvertCoefficient
              )
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          } else {
            tableInfo.value.data[index].details.push(detail)
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          }
        }
      } else {
        let newIndex = tableInfo.value.data.findIndex(
          (item) =>
            item.groupKey === mergeDetail.groupKey &&
            item.emptyRowType &&
            item.emptyRowType === '2'
        )
        if (newIndex > -1) {
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.value.data[newIndex] = mergeDetail
        } else {
          let spliceIndex = tableInfo.value.data.findIndex(
            (item) => item.depotStockId == list[list.length - 1].depotStockId
          )
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.value.data.splice(spliceIndex, 0, mergeDetail)
        }
      }
    } else {
      let list = tableInfo.value.data.filter((item) => item.depotStockId)
      mergeDetail.details = [detail]
      mergeDetail._key = detail._key
      if (list.length) {
        let index = tableInfo.value.data.findIndex(
          (item) => item.depotStockId == list[list.length - 1].depotStockId
        )
        tableInfo.value.data.splice(index + 1, 0, mergeDetail)
      } else {
        tableInfo.value.data.unshift(mergeDetail)
      }
      mergeDetail = countQty(mergeDetail)
      callback(false)
    }
  }
  setSuplierIdMap()
}
function getIndividualRight(ids) {
  return new Promise((resolve, reject) => {
    let param = {
      customizeUserVO: individualInfo.value.rightVo,
      queryMap: {
        id: {
          queryType: 'IN',
          queryCategory: 'AND',
          value: ids,
        },
      },
      queryParams: {},
    }
    purchReturnDetailsCustomizeListAll(param).then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        data.forEach((item) => {
          item.isChoice = false
        })
        resolve(data)
      } else {
        reject()
      }
    })
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function openDepotWindow() {
  depotInfo.value.visible = true
}
function openSupplierWindow() {
  selectProductSupplier.value.visible = true
}

function selectSupplierCallback(data) {
  if (data && data.supplierId) {
    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    formInfo.value.data['contact'] = data.contact
    formInfo.value.data['phone'] = data.phone
    scanInfo.value.query.queryParams.supplierId = data.supplierId
    tableInfo.value.data = []
  } else {
    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    formInfo.value.data['contact'] = ''
    formInfo.value.data['phone'] = ''
    tableInfo.value.data = []
  }
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}

//打开部门弹窗
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
//选择仓库返回
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    if (formInfo.value.data.depotId !== data.id) {
      formInfo.value.data.depotId = data.id
      formInfo.value.data.depotName = data.name
      formInfo.value.data.deptId = data.deptId
      formInfo.value.data.deptName = data.deptName
      formInfo.value.isCargoSpaceManage = data.isCargoSpaceManage
      scanInfo.value.query.queryParams.depotId = Number(data.id)
      tableInfo.value.data = []
      filterInfo.value.list.forEach((item) => {
        if (item.value === 'productCodeScan') {
          item.show = data.isCargoSpaceManage === 0
        }
      })
      if (data.isCargoSpaceManage === 1) {
        selectBatchInfo.value.tableKey =
          'productPurchReturnPageWmsAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      } else if (data.isCargoSpaceManage === 0) {
        selectBatchInfo.value.tableKey =
          'productPurchReturnPageAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      }
    }
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptId = ''
    formInfo.value.data.deptName = ''
    formInfo.value.isCargoSpaceManage = 0
    scanInfo.value.query.queryParams.depotId = ''
    tableInfo.value.data = []
    filterInfo.value.list.forEach((item) => {
      if (item.value === 'productCodeScan') {
        item.show = true
      }
    })
    selectBatchInfo.value.tableKey =
      'productPurchReturnPageAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
  }
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  const newDetailsList = tableInfo.value.data.filter(
    (row) => row.productId && row.depotStockId && row.calcQty > 0
  )
  if (!newDetailsList.length) {
    proxy.$message({
      message: '请选择有效产品',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let emptyDetails = newDetailsList
    .filter((item) => item.emptyRowType === '2')
    .map((item) => item.commonName)
  if (emptyDetails.length) {
    proxy.$message({
      message: '请添产品【' + emptyDetails + '】的批次信息',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let commonName = newDetailsList
    .filter((item) => item.calcQty > (item.stockAvailableCalcQty || 0))
    .map((item) => item.commonName)
  if (commonName.length) {
    proxy.$message({
      message: `产品【${commonName}】的退货数量不能大于库存可用数量，请修改`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let errMsg = []
  let receiptErr = []

  newDetailsList.forEach((item) => {
    if (
      item.needBatchNumber === 1 &&
      (!item.batchNumber || !item.productionDate || !item.validityDate)
    ) {
      errMsg.push(item.commonName)
    }

    if (
      !(item.receiptPrice && item.receiptCalcQty && item.receiptNumber) &&
      (item.receiptPrice || item.receiptCalcQty || item.receiptNumber)
    ) {
      receiptErr.push(item.commonName)
    }
  })
  if (receiptErr && receiptErr.length) {
    proxy.$message.warning(
      '请输入产品' + String(receiptErr) + '的开票数量/开票单价/开票号'
    )
    return
  }
  if (errMsg.toString()) {
    proxy.$message({
      message: '请选择产品' + errMsg + '的批号效期！',
      type: 'error',
      duration: 3500,
      showClose: true,
    })
    return
  }
  newDetailsList.map((item) => {
    let key = 'reason'
    if (item.details) {
      item.details.map((i) => {
        i[key] = item.reason
      })
    }
  })
  proxy.$fn.checkForm(formRefs.value).then(() => {
    getCoreSystemConfigAll().then((resp) => {
      if (resp && resp.success) {
        let find = resp.data.find(
          (item) => item.systemConfigCode === 'allow_expire_out'
        )
        if (find) {
          let expire = validateExpire(newDetailsList)
          if (find.value === '1') {
            if (expire) {
              proxy
                .$confirm(expire + ',是否继续?', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  dangerouslyUseHTMLString: true,
                })
                .then(() => {
                  const details = newDetailsList
                  const data = formInfo.value.data
                  data.mergeDetails = proxy.$fn.filterBlacklist(details)
                  const api = data.id
                    ? updatePurchReturnOrder
                    : isSaveAndSubmit === true
                    ? createPurchReturnOrderAndSave
                    : createPurchReturnOrder
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      proxy.$emit('returnModify', true)
                      showDialog.value = false
                    }
                  })
                  return
                })
                .catch(() => {
                  return
                })
            } else {
              const details = newDetailsList
              const data = formInfo.value.data
              data.mergeDetails = proxy.$fn.filterBlacklist(details)
              const api = data.id
                ? updatePurchReturnOrder
                : isSaveAndSubmit === true
                ? createPurchReturnOrderAndSave
                : createPurchReturnOrder
              api(data).then((resp) => {
                if (resp && resp.success) {
                  proxy.$emit('returnModify', true)
                  showDialog.value = false
                }
              })
              return
            }
          } else {
            if (expire) {
              proxy.$alert(expire + '，不允许出库！', '操作提示', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
              })
              return
            } else {
              const details = newDetailsList
              const data = formInfo.value.data
              data.mergeDetails = proxy.$fn.filterBlacklist(details)
              const api = data.id
                ? updatePurchReturnOrder
                : isSaveAndSubmit === true
                ? createPurchReturnOrderAndSave
                : createPurchReturnOrder
              api(data).then((resp) => {
                if (resp && resp.success) {
                  proxy.$emit('returnModify', true)
                  showDialog.value = false
                }
              })
              return
            }
          }
        } else {
          const details = newDetailsList
          const data = formInfo.value.data
          data.mergeDetails = proxy.$fn.filterBlacklist(details)
          const api = data.id
            ? updatePurchReturnOrder
            : isSaveAndSubmit === true
            ? createPurchReturnOrderAndSave
            : createPurchReturnOrder
          api(data).then((resp) => {
            if (resp && resp.success) {
              proxy.$emit('returnModify', true)
              showDialog.value = false
            }
          })
        }
      }
    })
  })
}

const purchAccording = ref(props.purchAccording)
function getMain() {
  detailPurchReturn(props.purchReturnId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      formInfo.value.isCargoSpaceManage = resp.data.isCargoSpaceManage
      formInfo.value.data.returnType = String(resp.data.returnType)
      scanInfo.value.query.queryParams.depotId = resp.data.depotId
      scanInfo.value.query.queryParams.supplierId = resp.data.supplierId
      selectProductInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      selectBatchInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.leftQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.rightQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      scanInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      filterInfo.value.list.forEach((item) => {
        if (item.value === 'productCodeScan') {
          item.show = resp.data.isCargoSpaceManage === 0
        }
      })
      if (resp.data.isCargoSpaceManage === 1) {
        selectBatchInfo.value.tableKey =
          'productPurchReturnPageWmsAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      } else if (resp.data.isCargoSpaceManage === 0) {
        selectBatchInfo.value.tableKey =
          'productPurchReturnPageAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      }
      if (resp.data.purchAccording) {
        purchAccording.value = resp.data.purchAccording
        selectProductInfo.value.query.queryParams['purchAccording'] =
          resp.data.purchAccording
        individualInfo.value.leftQuery.queryParams['purchAccording'] =
          resp.data.purchAccording
        selectBatchInfo.value.query.queryParams['purchAccording'] =
          resp.data.purchAccording
        scanInfo.value.query.queryParams['purchAccording'] =
          resp.data.purchAccording
        setPurchAccording()
      }
      if (
        !(
          resp.data.purchAccording == '2' ||
          proxy.$store.state.permission.systemConfig.purch_according == '2'
        )
      ) {
        tableInfo.value.fieldList = tableInfo.value.fieldList.filter(
          (item) => item.value !== 'quoteContractNo'
        )
        setBusinessDate()
      }
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.purchReturnId
  getList()
}
function getList() {
  //修改请求明细信息
  purchReturnDetailsCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let isCargoSpaceManage = formInfo.value.isCargoSpaceManage
      let data = resp.data
      data.forEach((row) => {
        let str = ''
        row.calcQty = Math.abs(row.calcQty || 0)
        row.largeUnitQty = Math.abs(row.largeUnitQty || 0)
        row.smallUnitQty = Math.abs(row.smallUnitQty || 0)
        row.qty = Math.abs(row.qty || 0)
        row.sumAmount = Math.abs(row.sumAmount || 0)
        tableInfo.value.sysGroup.forEach((item) => {
          if (
            item !== 'price' &&
            item !== 'supplierId' &&
            item !== 'storeBatchNumber' &&
            item !== 'isConsignBusiness'
          ) {
            if (item === 'productionDate' || item === 'validityDate') {
              str = str + (row[item] || '1900-01-01') + ''
            } else {
              str = str + row[item] + ''
            }
          }
        })
        row.groupKey = str
        row._key =
          row.storeBatchNumber +
          '-' +
          row.supplierId +
          '-' +
          row.price +
          '-' +
          row.isConsignBusiness
        if (
          (isCargoSpaceManage === 1 ||
            row.codeType === 1 ||
            row.codeType === 4) &&
          row.calcQty > (row.stockAvailableCalcQty || 0)
        ) {
          row.calcQty = proxy.$fn.deepClone(row.stockAvailableCalcQty || 0)
          let unitConvertCoefficient = row.unitConvertCoefficient || 1
          row.qty = proxy.$fn.accDiv(row.calcQty, unitConvertCoefficient)
          row.largeUnitQty = parseInt(row.calcQty / unitConvertCoefficient)
          row.smallUnitQty = parseInt(row.calcQty % unitConvertCoefficient)
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(row.calcQty, row.price || 0),
            unitConvertCoefficient
          )
        }
        if (
          isCargoSpaceManage === 1 ||
          row.codeType === 1 ||
          row.codeType === 4
        ) {
          let detail = proxy.$fn.deepClone(row)
          row.details = [detail]
        }
      })
      tableInfo.value.data = data
      tableInfo.value.data.push({
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      })
      // tableInfo.value.data.map((item) => {
      //   item.reason = String(item.reason)
      // })
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'purchReturnProductBatchModify-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel })
        }
      }
      arr = proxy.$fn.getSort(arr, 'sysGroupLevel')
      arr = arr.map((element) => {
        return element.key
      })
      selectBatchInfo.value.query.queryParams.groupField = arr.length
        ? arr.toString()
        : ''
      individualInfo.value.leftQuery.queryParams.groupField = arr.length
        ? arr.toString()
        : ''
      tableInfo.value.sysGroup = arr
      if (props.purchReturnId) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getProductCustomize() {
  //库存产品弹窗配置
  let param = {
    tableKey:
      'productPurchReturnPageAddProduct-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({
            columnName: data.detail[key].columnName,
            asTbName: data.detail[key].asTbName,
            key: key,
          })
        }
      }
      tableInfo.value.productSysGroup = arr
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'purchPurchReturnProductIndividualRight-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      individualInfo.value.rightVo = data
    }
  })
}
function getScanCustomize() {
  let param = {
    tableKey:
      'purchPurchReturnProductBatchScan-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      scanInfo.value.query.customizeUserVO = data
    }
  })
}
function getwmsBatchCustomize() {
  let param = {
    tableKey:
      'productPurchReturnPageWmsAddBatch-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          console.log(key)
          if (key === 'productionDate' || key === 'validityDate') {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              ignoreEmptyValue: false,
              key: key,
            })
          } else {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
          }
        }
      }
      tableInfo.value.batchSysGroup = arr
    }
  })
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.purchReturnId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
  proxy.$fn.setFieldListColWidth(
    tableInfo.value.fieldList,
    tableInfo.value.bigWidth,
    tableInfo.value.smallWidth
  )
})
setPurchAccording()
getwmsBatchCustomize()
getCustomize()
getProductCustomize()
getScanCustomize()
getInvdividualRightCustomize()
function setPurchAccording() {
  let _changeContract = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换合同',
  ])
  _changeContract.show = false
  if (
    parseInt(props.purchAccording) === 2 ||
    parseInt(purchAccording.value) === 2
  ) {
    _changeContract.show = true
  }
}
</script>

<style scoped>
.el-input-search {
  width: 100%;
  height: 100%;
}
</style>
